package com.ruoyi.api;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.wx.domain.WxUser;
import com.ruoyi.wx.service.IWxUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: wind
 * @CreateTime: 2020-05-04
 * @Description:用户
 */

@RestController
@RequestMapping("/api/users")
public class ApiUserController {
    @Autowired
    private IWxUserService wxUserService;


    private static String mini_appID = "wx34334a74da1fe88e";//appid，去自己的小程序后台找
    private static String mini_secret = "eca32be55f2458e3720fafa7242ff7fa";//appsecret，去自己小程序后台找
    private static String grant_type = "authorization_code";


    @RequestMapping("/wxlogin")
    public AjaxResult getOpenId(String code) {
        Map<String, String> res = new HashMap<>();
        String result = "";
        try {//请求微信服务器，用code换取openid。HttpUtil是工具类，后面会给出实现，Configure类是小程序配置信息，后面会给出代码
            result = HttpUtils.sendGet(
                    "https://api.weixin.qq.com/sns/jscode2session?appid="
                            + mini_appID + "&secret="
                            + mini_secret + "&js_code="
                            + code
                            + "&grant_type=authorization_code", null);

            System.out.println(result);
            JSONObject jsonObj = JSONObject.parseObject(result);//解析从微信服务器上获取到的json字符串
            System.out.println("用户的openid为：" + jsonObj.get("openid"));//此处也可以得到session_key的值
            res.put("session_key", jsonObj.get("session_key").toString());

            WxUser custUser = wxUserService.getOne(new QueryWrapper<>(new WxUser().setOpenId(jsonObj.get("openid").toString())));//去数据库判断用户是否存在该用户
            if (custUser != null)//如果存在该用户
            {
                return AjaxResult.success(custUser);
            }
            //如果是新用户，就添加用户到数据库中
            WxUser frontUserInfo = new WxUser();//封装小程序对象
            frontUserInfo.setOpenId(jsonObj.get("openid").toString());
            //将用户信息保存到数据库中
            wxUserService.save(frontUserInfo);

            return AjaxResult.success(frontUserInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error();
        }
    }

    @RequestMapping("/update")
    public AjaxResult updateUser(WxUser wxUser){
        return AjaxResult.success(wxUserService.saveOrUpdate(wxUser));
    }
}
